package com.cbgolf.oa.adapter;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.event.Events;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import org.greenrobot.eventbus.EventBus;


/**
 * Created by seiya on 2016/11/17.
 */
public class CalendarAdapter extends BaseAdapter {

  private Context context;
  private LayoutInflater mInflater;
  private int year;
  private int month;

  private List<Integer> list = new ArrayList<>();
  private String[] weeks = new String[]{"日", "一", "二", "三", "四", "五", "六"};
  private String week;
  private int day = 1;

  private Calendar calendar;
  private int curYear;
  private int curMonth;
  private int today;
  private int chooseYear;
  private int chooseMonth;
  private int chooseDay;
  private Handler handler;
  int weekIndex;

  public CalendarAdapter(Context context, int year, int month, int day, Handler handler) {
    this.context = context;
    mInflater = LayoutInflater.from(context);
    this.chooseYear = year;
    this.chooseMonth = month;
    this.chooseDay = day;
    calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    curYear = calendar.get(Calendar.YEAR);
    curMonth = calendar.get(Calendar.MONTH) + 1;
    today = calendar.get(Calendar.DAY_OF_MONTH);
    this.handler = handler;
    initList();
  }

  public CalendarAdapter(Context context, long time) {
    this.context = context;
    mInflater = LayoutInflater.from(context);
    if (time > 0) {
      this.chooseYear = DateUtil.getYear(time);
      this.chooseMonth = DateUtil.getMonth(time);
      this.chooseDay = DateUtil.getDay(time);
    }
    calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    curYear = calendar.get(Calendar.YEAR);
    curMonth = calendar.get(Calendar.MONTH) + 1;
    today = calendar.get(Calendar.DAY_OF_MONTH);
//    this.handler = handler;
    initList();
  }

  public void clear() {
    if (null != list && list.size() > 0) {
      list.clear();
    }
  }

  public void setData(int year, int month) {
    this.year = year;
    this.month = month;
    initList();
  }

  public void upDataUI() {
    this.notifyDataSetChanged();
  }

  private void initList() {
    if (year == 0) {
      year = chooseYear;
    }
    if (month == 0) {
      month = chooseMonth;
    }
    weekIndex = getWeek(year, month, day);
//        week = weeks[weekIndex];
    int dayNum = getDaysOfMonth(year, month);

    int bMonth = month - 1;
    int bYear = year;
//        int afMonth = month + 1;
//        int afYear = year;
    if (bMonth == 0) {
      bMonth = 12;
      bYear = year - 1;
    }
//        if (afMonth > 12) {
//            afMonth = 1;
//            afYear = year + 1;
//        }
    int bNum = getDaysOfMonth(bYear, bMonth);
//        int afNum = getDaysOfMonth(afYear, afMonth);
    int afDay = 1;
    for (int i = 0; i < 7; i++) {
      if (weekIndex == i) {
        break;
      }
      list.add(0);
      bNum--;
    }
    int size = list.size();
    if (size > 0) {
      Collections.reverse(list);
    }
    if ((size + dayNum) > 35) {
      for (int i = 1; i <= 42 - size; i++) {
        if (i <= dayNum) {
          list.add(i);
        } else {
          list.add(0);
          afDay++;
        }

      }
    } else {
      for (int i = 1; i <= 35 - size; i++) {
        if (i <= dayNum) {
          list.add(i);
        } else {
          list.add(0);
          afDay++;
        }
      }
    }
  }

  private int getDaysOfMonth(int year, int month) {
    int days = 31;
    switch (month) {
      case 4:
      case 6:
      case 9:
      case 11:
        days = 30;
        break;
      case 2:
        days = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? 29 : 28;
        break;
    }
    return days;
  }

  /**
   * 1-6 代表星期一至星期六 0 代表星期日
   * 如果返回 -1 表示参数不正确
   */
  public static int getWeek(int y, int m, int d) {
    if (m < 1 || m > 12 || d < 1 || d > 31) {
      return -1;
    }
    if (m == 1) {
      m = 13;
      y--;
    } else if (m == 2) {
      m = 14;
      y--;
    }
    int c = y / 100;
    y = y - c * 100;
    int week = y + y / 4 + c / 4 - 2 * c + 26 * (m + 1) / 10 + d - 1;
    week %= 7;
    week = week < 0 ? week + 7 : week;
    return week;
  }


  @Override
  public int getCount() {
    // TODO Auto-generated method stub
    return list.size();
  }

  @Override
  public Object getItem(int position) {
    // TODO Auto-generated method stub
    return list.get(position);
  }

  @Override
  public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
  }

  @Override
  public View getView(int position, View view, ViewGroup parent) {
    Holder h = null;
    if (null == view) {
      h = new Holder();
      view = mInflater.inflate(R.layout.item_calendar_date, null);
      h.dateTv = (TextView) view.findViewById(R.id.item_date_date_tv);
      h.dateView = view.findViewById(R.id.item_date_date_ll);
      h.itemView = view.findViewById(R.id.item_date_layout_ll);
      view.setTag(h);
      AutoUtil.auto(view);

    } else {
      h = (Holder) view.getTag();
    }
    final int d = list.get(position);
    if (d != 0) {
      h.dateTv.setText(d + "");
      h.dateView.setEnabled(true);
      if (d == chooseDay && year == chooseYear && month == chooseMonth) {
        h.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_blue));
        h.dateTv.setTextColor(Color.parseColor("#ffffff"));
      } else {
        h.itemView.setBackgroundColor(Color.parseColor("#e6e6e6"));
        h.dateTv.setTextColor(Color.parseColor("#747474"));
      }
    } else {
      h.dateTv.setText("");
      h.itemView.setBackgroundColor(Color.parseColor("#eeeeee"));
      h.dateTv.setTextColor(Color.parseColor("#d7d7d7"));
      h.dateView.setEnabled(false);

    }
    h.dateView.setOnClickListener(v -> {
      Message msg = new Message();
      Bundle bundle = new Bundle();
      bundle.putInt("year", year);
      bundle.putInt("month", month);
      bundle.putInt("day", d);
      msg.setData(bundle);
      if (null != handler) {
        handler.sendMessage(msg);
      }
      EventBus.getDefault().post(new Events.Builder()
          .msgTarget(DataManager.TEETIME_CALENDAR_CHOICE)
          .selectTime(DateUtil.getTimeByYMD(year, month, d))
          .build());
    });
    return view;
  }

  class Holder {

    private View itemView;
    private View dateView;
    private TextView dateTv;

  }

}
